<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\GoodsCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\GoodsCategory AS GoodsCategoryModel;
use Request;
class GoodsCategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new GoodsCategory(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column("order_number")->editable()->sortable();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->like("name");
            });
            // 也可以这样
            $grid->disableBatchDelete();
            // 禁用详情按钮
            $grid->disableViewButton();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new GoodsCategory(), function (Show $show) {
            $show->field('id');
            $show->field('name');

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new GoodsCategory(), function (Form $form) {
            $form->text('name')->rules('required');
            $form->number("order_number");
            // 复杂的验证规则可以在回调里面实现
//            $form->select('parent_id',"父类")->rules(function ($form) {
//                // 如果不是编辑状态，则添加字段唯一验证
//                if ($form->parent_id==$form->model()->id){
//                    $form->responseValidationMessages('parent_id', '不能成为自己的父类');
//                }
//                $parent_level = GoodsCategoryModel::where("id",$form->parent_id)->value("level");
//                if ($parent_level>=2){
//                    $form->responseValidationMessages('parent_id', '最多有划分三级目录');
//                }
//
//                //保存之后的后续事件
//                $form->saved(function (Form $form, $result) {
//                    // 判断是否是新增操作
//                    $goodsCategory = GoodsCategoryModel::where("id",$result)->first();
//                    $parent_info = GoodsCategoryModel::where("id",$goodsCategory->parent_id)->first();
//                    if ($parent_info){
//                        $data['level'] = $parent_info->level+1;
//                        $data['path'] = $parent_info->path."-".$goodsCategory->id;
//                    }else{
//                        $data['level'] = 0;
//                        $data['path'] = $goodsCategory->id;
//                    }
//                    $goodsCategory->update($data);
//
//                    // 修改操作
//                });
//
//            })->options(GoodsCategoryModel::goodsCategoryShow());
        });
    }
}
